package ink.lovejinhu.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jinhu
 * created 2021-07-20 18:00
 */
public class ThreadCommunication {
    public static void main(String[] args) {
        Share share = new Share(10, 20);
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    share.consume();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "consume01").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++) {
                    share.consume();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "consume02").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 30; i++) {
                    share.produce();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "produce01").start();
    }
}

class Share {
    private int number;   //现在仓库的数量
    private int capcity;   //仓库最大的容量
    public ReentrantLock lock = new ReentrantLock();

    public Share(int number, int capcity) {
        this.number = number;
        this.capcity = capcity;
    }

    public synchronized void produce() throws InterruptedException {
        while (number > capcity) {  //如果现在数量大于了最大容量
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "生产了一个，number的数量是:" + number);
        this.notifyAll();
    }

    public synchronized void consume() throws InterruptedException {
        while (number <= 0) {
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "消费了一个，number的数量是:" + number);
        this.notifyAll();
    }
}